<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ChannelCode\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Codec\Json;
use MoChat\Plugin\ChannelCode\Contract\ChannelCodeContract;
use MoChat\Plugin\ChannelCode\Logic\Traits\ChannelCodeTrait;
use Psr\Container\ContainerInterface;

/**
 * 处理渠道码脚本逻辑.
 *
 * Class ChannelCodeLogic
 */
class ChannelCodeLogic
{
    use ChannelCodeTrait;

    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * 渠道码表.
     * @Inject
     * @var ChannelCodeContract
     */
    private $channelCode;

    /**
     * @param mixed $isTask
     * @return array|void
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle($isTask = false)
    {
        $this->logger = $this->container->get(StdoutLoggerInterface::class);
        // 查询所有渠道码
        $info = $this->channelCode->getChannelCodes();
        if (empty($info)) {
            return;
        }

        foreach ($info as &$value) {
            $drainageEmployee = Json::decode($value['drainageEmployee'], true);

            try {
                // 更新二维码
                $this->handleQrCode(
                    $drainageEmployee,
                    (int) $value['autoAddFriend'],
                    (int) $value['corpId'],
                    (int) $value['id'],
                    $value['wxConfigId']
                );
            } catch (\Throwable $e) {
                if (! $isTask) {
                    $this->logger->error(sprintf('[ChannelCodeLogic错误:] %s, error:%s', $value['drainageEmployee'], $e->getMessage()));
                }
            }
        }
        unset($value);
    }
}
